package com.bjpowernode.p2p.service.loan.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.bjpowernode.p2p.constant.Dubbo;
import com.bjpowernode.p2p.constant.Redis;
import com.bjpowernode.p2p.dao.LoanDao;
import com.bjpowernode.p2p.entity.LoanInfo;
import com.bjpowernode.p2p.entity.UserRanking;
import com.bjpowernode.p2p.service.loan.LoanListService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
@Service(interfaceClass = LoanListService.class,version = "1.0",timeout = Dubbo.TIMEOUT)
public class LoanListServiceImpl implements LoanListService {
    @Autowired
    LoanDao loanDao;

    @Autowired
    RedisTemplate<Object,Object> redisTemplate;


    @Override
    public List<LoanInfo> queryByproductType(HashMap<String, Object> paramMap) {
        //数据量少，更新少，访问平凡，有可能形成高并发的需要做缓存策略，例如首页，一周排行等数据展示
        //分页数据，基本数据查看无需缓存（但也不是绝对，比如电视多产品抢购等）
        //目前内页列表无需缓存（因为涉及到分页，以及后台数据变更平反，内页列表访问量不是特别频繁，因此加入缓存只会增加系统复杂度，带来维护上的麻烦）
        return loanDao.findListByproductType(paramMap);
    }
    @Override
    public int countLoanQueryByproductType(int productType) {
        return loanDao.countLoanFindByproductType(productType);
    }

    @Override
    public List<UserRanking> queryUserRankingService() {
        List<UserRanking> userRankingList = (List<UserRanking>)redisTemplate.opsForValue().get(Redis.USERRANKING_KEY);
        if(!ObjectUtils.allNotNull(userRankingList)) {
            synchronized (this) {
                userRankingList = (List<UserRanking>) redisTemplate.opsForValue().get(Redis.USERRANKING_KEY);
                if (!ObjectUtils.allNotNull(userRankingList)) {
                    log.info("数据库查询userRankingList...................");
                    userRankingList = loanDao.findUserRankingService();
                    redisTemplate.opsForValue().set(Redis.USERRANKING_KEY, userRankingList, 1, TimeUnit.DAYS);
                }
            }
        }
        return userRankingList;
    }
}
